import { useMemo, Fragment, forwardRef, useCallback, useImperativeHandle } from 'react';
import { createPortal } from 'react-dom';
import throttle from 'lodash.throttle';
import { Menu as ReactContexifyMenu, Item, Separator, useContextMenu } from 'react-contexify';
import { CopyOutlined, EditOutlined, DeleteOutlined, CloudDownloadOutlined } from '@ant-design/icons';

import type { Props, MenuRef } from './interface';

import styles from './index.module.scss';
import 'react-contexify/ReactContexify.css';

/** 图标映射 */
const ICON_MAP = {
  copy: CopyOutlined,
  edit: EditOutlined,
  delete: DeleteOutlined,
  download: CloudDownloadOutlined,
};

/**
 * 右击菜单
 */
const Menu = forwardRef<MenuRef, Props>((props, ref) => {
  const { id, items } = props;

  const { show: menuShow, hideAll } = useContextMenu({ id });

  const content = useMemo(() => {
    return items.map(({ icon, name, onClick }, index) => {
      const Icon = ICON_MAP[icon];
      return (
        <Fragment key={index}>
          <Separator x-if={index > 0} />
          <Item
            onClick={() => {
              hideAll();
              onClick();
            }}
          >
            <Icon className={styles.icon} />
            {name}
          </Item>
        </Fragment>
      );
    });
  }, [items, hideAll]);

  /**
   * 显示菜单
   */
  const show = useCallback(
    throttle<MenuRef['show']>((params) => menuShow(params), 300, { trailing: false }) as MenuRef['show'],
    [menuShow],
  );

  useImperativeHandle(ref, () => ({ show, hideAll }));

  return createPortal(<ReactContexifyMenu id={id}>{content}</ReactContexifyMenu>, document.body);
});

export default Menu;
